#include "Thread.h"
#include "CurrentThread.h"

#include <sstream>
#include <iosfwd>
#include <semaphore.h>

std::atomic<int32_t> m_numCreated {0};

Thread::Thread(Functor cb, const std::string& name)
   : m_started(false)
   , m_joined(false)
   , m_pid(0)
   , m_func(std::move(cb))
   , m_threadName(name)
{
  //setDefaultName();
}

Thread::~Thread()
{
  if (m_started && !m_joined) {
    join();
  }
}

// void Thread::setDefaultName()
// {
//   if (m_threadName.empty()) {
//     std::ostringstream oss;
//     oss << "Thread#" << ++m_numCreated;
//     m_threadName = oss.str();
//   }
// }

void Thread::start() // 一个 thread 对象就是一个新线程的详细信息
{
  m_started = true;
  sem_t sem;
  sem_init(&sem, false, 0);
  m_thread = std::make_shared<std::thread>([&]() { m_pid = CurrentThread::tid(); sem_post(&sem), m_func(); });
  sem_wait(&sem);
}

void Thread::join()
{
  m_joined = true;
  m_thread->join();
}

